from point import Point
from arrangement import Arrangement
from problem import Problem
IS_DEBUG = True
DEBUG_FILE_PATH = r"input.txt"
ALLOW_PROMPT = False

def prompt_out(text):
    if (ALLOW_PROMPT):
        print text,

class FileInput(object):
    def __init__(self, file_path):
        self._file_path = file_path
        self._data = file(file_path, "rb").read().replace("\r", "")
        self._all_data = self._data
    @property
    def data(self):
        return self._data
    @property
    def all_data(self):
        return self._all_data
    def read_line(self, prompt = ""):
        prompt_out(prompt)
        value = self._data.split("\n", 1)
        if (len(value) < 2):
            value.append("")
        line, self._data = value
        prompt_out(line + "\n")
        return line

class UserInput(object):
    def __init__(self):
        pass
    def read_line(self, prompt = ""):
        if (not ALLOW_PROMPT):
            prompt = ""
        return raw_input(prompt)
    
class ConfigurationError(Exception):
    def __init__(self, line, error):
        Exception.__init__(self, "Line: " + str(line) + "\n" + error)

class ConfigurationReader(object):
    def __init__(self, file_path = None):
        if file_path != None:
            self._input = FileInput(file_path)
        else:
            self._input = UserInput()
        self._line_index = 0
    @property
    def line_index(self):
        return self._line_index
    def _read_line(self, prompt = ""):
        line = self._input.read_line(prompt)
        self._line_index += 1
        return line
    def _read_line_int(self, prompt = ""):
        try:
            value = int(self._read_line(prompt))
            return value
        except ValueError:
            raise ConfigurationError(self.line_index, "Expected integer")
    def read_polygon(self):
        count = self._read_line_int("Polygon vertices number:")
        arr = Arrangement()
        line = self._read_line()
        cols = line.split(" ")
        if (len(cols)/2.0 != count):
            raise ConfigurationError(self.line_index, "Epected " + str(count) + " vertices")
        for i in xrange(len(cols)/2):
            arr.add(Point(float(cols[i*2]), float(cols[i*2 + 1])))
        return arr
    def read_problem(self):
        prompt_out("Robot:\n")
        robot = self.read_polygon()
        prompt_out("Room:\n")
        room = self.read_polygon()
        return Problem(room, robot)